#![allow(dead_code)]

use super::trader_virtual;
use away_core::backgroup_service::*;
use away_db::trader_repository::*;
use away_stock_data::market::*;
use sea_orm::DbConn;

pub fn start(db: DbConn) {
    // 开市任务
    job_params(
        "0/5 * 9,10,11,13,14 * * 1,2,3,4,5 ",
        db.clone(),
        |db| async move {
            tracing::info!("开市任务");
            trader_start(&db).await;
        },
    );

    // 休市任务
    job_params("0 0,30 16 * * 1,2,3,4,5 *", db.clone(), |db| async move {
        tracing::info!("休市任务");
        trader_end(&db).await;
    });
}

async fn trader_start(db: &DbConn) {
    let res = stock_trade_job_rep::all(db).await;
    if res.is_err() {
        return;
    }
    let stock_list = res
        .unwrap()
        .into_iter()
        .map(|o| o.stock_code)
        .collect::<Vec<String>>();
    let stock_codes = stock_list.join(",");

    let market_res = get_market_list(stock_codes.as_str()).await;
    let mut index = 0;
    if let Ok(markets) = market_res {
        for market in markets {
            let codes = stock_list.clone();
            let stock_code = &codes[index];
            index += 1;
            trader_virtual::trade_start(db, stock_code.as_str(), market.now_price).await;
        }
    }
}
async fn trader_end(db: &DbConn) {
    trader_virtual::trade_end(db).await;
}
